package com.liu.nb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liu.nb.entity.Page;
import com.liu.nb.entity.RolePage;
import com.liu.nb.entity.UserRole;
import com.liu.nb.mapper.PageMapper;
import com.liu.nb.service.IPageService;
import com.liu.nb.service.IRolePageService;
import com.liu.nb.service.IUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 权限和页面表 服务实现类
 * </p>
 *
 * @author liuziyi
 * @since 2021-08-31
 */
@Service
public class PageServiceImpl extends ServiceImpl<PageMapper, Page> implements IPageService {
    @Autowired
    private IUserRoleService userRoleService;
    @Autowired
    private IRolePageService rolePageService;

    @Override
    public List<Page> getUserNav(Integer id) {
        /*
        * 获取用户角色
        * */
        UserRole one = userRoleService.getOne(new QueryWrapper<UserRole>().eq("user_id",id));
        /*先获得该用户的所有权限信息*/
        List<Page> list = this.list(new QueryWrapper<Page>().inSql("id","SELECT page_id FROM role_page WHERE role_id="+one.getRoleId()));
        /*转成树状结构*/
        return buildTreeMenu(list);
    }

    /**
     * 获取所有系统功能菜单树
     */
    @Override
    public List<Page> getAllPremAndPage() {
        List<Page> list = this.list();
        return buildTreeMenu(list);
    }

    @Override
    public List<Integer> getPermIdsByRole(Integer id) {
        List<RolePage> list = rolePageService.list(new QueryWrapper<RolePage>().eq("role_id",id).select("page_id"));
        List<Integer> collect = list.stream().map(i -> i.getPageId()).collect(Collectors.toList());
        return collect;
    }

    /*
    * 把page转树状结构
    * */
    private List<Page> buildTreeMenu(List<Page> pages){
        List<Page> treePage=new ArrayList<>();
        for (Page page : pages) {
            for (Page p : pages) {
                /*如果id和parendId相等*/
                if (p.getParentId()==page.getId()){
                    page.getChildren().add(p);
                }
            }
            /*如果节点的parentID为0那么它就是顶级元素*/
            if (page.getParentId()==0) {
                treePage.add(page);
            }
        }
        return treePage;
    }


}
